import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Random;

/**
 * Created with IntelliJ IDEA
 * Description 管道输入输出流实现 生产者消费者模型 1 vs 1
 * User: 王杰
 * Date: 2025-05-18
 * Time: 0:08
 */
public class PipedTest {
    private final PipedInputStream pis = new PipedInputStream();
    private final PipedOutputStream pos = new PipedOutputStream();

    {
        try {
            pis.connect(pos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Producer implements Runnable {

        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(1000);
                    int num = (int) (255 * Math.random());
                    System.out.println(Thread.currentThread().getName() + "生产者生产了一个数字，该数字为" + num);
                    pos.write(num);
                    pos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    pos.close();
                    pis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(1000);
                    int num = pis.read();
                    System.out.println("消费者消费了一个数字，该数字为：" + num);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    pos.close();
                    pis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static void main(String[] args) {
        PipedTest pipedTest = new PipedTest();
        new Thread(pipedTest.new Producer()).start();
        new Thread(pipedTest.new Consumer()).start();

    }
}
